package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.ExchangeRecordMapper;
import com.graduation.springbootinit.model.entity.ActivityPart.ExchangeRecord;
import com.graduation.springbootinit.model.entity.ShopPart.AddressBook;
import com.graduation.springbootinit.service.AddressBookService;
import com.graduation.springbootinit.service.ExchangeRecordService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class ExchangeRecordServiceImpl extends ServiceImpl<ExchangeRecordMapper, ExchangeRecord>
        implements ExchangeRecordService {

    @Resource
    private AddressBookService addressBookService;

    @Override
    public Page<ExchangeRecord> getUserExchangeRecords(Long userId, int pageNum, int pageSize) {
        Page<ExchangeRecord> page = new Page<>(pageNum, pageSize);
        return baseMapper.selectPageByUserId(page, userId);
    }

    @Override
    public void updateStatus(Long recordId, Integer status) {
        // 验证状态值
        if (status < 0 || status > 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的状态值");
        }
        
        // 验证记录是否存在
        ExchangeRecord record = getById(recordId);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "兑换记录不存在");
        }
        
        // 更新状态
        baseMapper.updateStatus(recordId, status);
    }

    @Override
    public ExchangeRecord getRecordDetail(Long recordId) {
        ExchangeRecord record = getById(recordId);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "兑换记录不存在");
        }
        
        // 填充地址信息
        AddressBook address = addressBookService.getById(record.getAddressId());
        if (address != null) {
            record.setAddressInfo(address.getProvinceName() + address.getCityName() + 
                    address.getDistrictName() + address.getDetail());
        }
        
        return record;
    }

    @Override
    public Page<ExchangeRecord> getPendingRecords(int pageNum, int pageSize) {
        Page<ExchangeRecord> page = new Page<>(pageNum, pageSize);
        page = baseMapper.selectPendingRecords(page);
        
        // 填充所有记录的地址信息
        for (ExchangeRecord record : page.getRecords()) {
            AddressBook address = addressBookService.getById(record.getAddressId());
            if (address != null) {
                record.setAddressInfo(address.getProvinceName() + address.getCityName() + 
                        address.getDistrictName() + address.getDetail());
            }
        }
        
        return page;
    }
} 